package engine.BIEngine0_1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.hadoop.util.Time;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import beans.BaseResourceState;
import beans.FileStatus;
import beans.FullJobState;
import beans.HistoryTask;
import beans.HttpConfig;
import beans.HttpResult;
import beans.HttpResultList;
import beans.LCStoreModel;
import beans.PhysicalBlockInfor;
import beans.TokenValue;
import net.CommitJob;
import net.HttpRequest;
//import net.sf.json.JSONArray;
//import net.sf.json.JSONObject;
import net.HttpsRequest;
import portal.common.MyStringUtils;
import utils.JsonUtil;
import utils.Log4jInit;
import utils.SortFile;
import utils.StaticUtil;
import utils.StreamGobbler;

@SuppressWarnings("Duplicates")
public class AlgorithmOperator {

	/**
	 * with physical blocks fake oneBlock:PhysicalBlockInfor get blocks' path by
	 * input file path configPath will read by http.properties
	 *
	 * @param filePath
	 * @return
	 */
	/*
	 * public static HttpResultList getBlocksByPathUri(int numOfBlocks, String
	 * filePath) { String configPath = HttpConfig.configPath; // int numOfBlocks
	 * = (int) (Math.random()*4+1); filePath = filePath.substring(0,
	 * filePath.lastIndexOf("/") + 1); JSONArray results =
	 * produceFakeBlocks(numOfBlocks, filePath); List<Object> blocks = new
	 * ArrayList<>(); for (int i = 0; i < results.size(); i++) { JSONObject
	 * result = results.getJSONObject(i); JSONArray hosts =
	 * result.getJSONArray("hosts"); List<String> hostNames = new ArrayList<>();
	 * for (int j = 0; j < hosts.size(); j++) {
	 * hostNames.add(hosts.getJSONObject(j).getString("hostName")); }
	 * PhysicalBlockInfor oneBlock = new
	 * PhysicalBlockInfor(result.getString("blk"), hostNames);
	 * blocks.add(oneBlock); } HttpResultList result = new HttpResultList(true,
	 * "", blocks); return result;
	 * 
	 * }
	 */

	// private static final transient Logger log =
	// Logger.getLogger(AlgorithmOperator.class);

	public static HttpResultList getBlocksByPathUri(int numOfBlocks, String filePath) {
		String configPath = HttpConfig.configPath;
		// int numOfBlocks = (int) (Math.random()*4+1);
		// filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
		// JSONArray results = produceFakeBlocks(numOfBlocks, filePath);
		List<Object> blocks = new ArrayList<>();
		// Log4jInit.logger.info("filePath:::"+filePath);

		// filePath = filePath.replaceAll("/","\\\\");
		PhysicalBlockInfor oneBlock = new PhysicalBlockInfor(filePath, null);
		blocks.add(oneBlock);

		return new HttpResultList(true, "", blocks);

	}

	/**
	 * real oneBlock:PhysicalBlockInfor get blocks' path by input file path
	 * configPath will read by http.properties
	 *
	 * @param filePath
	 * @return
	 */
	public static HttpResultList getBlocksByPathUri(String filePath) {
		String configPath = HttpConfig.configPath;
		int numOfBlocks = (int) (Math.random() * 4 + 1);
		filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
		JSONArray results = produceFakeBlocks(numOfBlocks, filePath);
		List<Object> blocks = new ArrayList<>();
		for (int i = 0; i < results.size(); i++) {
			JSONObject result = results.getJSONObject(i);
			JSONArray hosts = result.getJSONArray("hosts");
			List<String> hostNames = new ArrayList<>();
			for (int j = 0; j < hosts.size(); j++) {
				hostNames.add(hosts.getJSONObject(j).getString("hostName"));
			}
			PhysicalBlockInfor oneBlock = new PhysicalBlockInfor(result.getString("blk"), hostNames);
			blocks.add(oneBlock);
		}
		return new HttpResultList(true, "", blocks);

	}

	private static JSONArray produceBlocks(String filePath) {
		// Ccnbjk.getBlkInfo()
		return null;
	}

	/**
	 * fake produce blocks information
	 *
	 * @param num
	 * @return
	 */
	private static JSONArray produceFakeBlocks(int num, String filePath) {
		JSONArray results = new JSONArray();
		for (int i = 0; i < num; i++) {
			int numOfHosts = (int) (Math.random() * 3 + 1);
			JSONObject result = new JSONObject();
			// value:/home/blocks/temp/<numOfHosts>/<i+1>.jpg
			result.put("blk", filePath + "physcialPath" + "/" + (i + 1) + "_"
					+ UUID.randomUUID().toString().substring(0, 20) + ".jpg");
			JSONArray hosts = new JSONArray();
			for (int j = 0; j < numOfHosts; j++) {
				JSONObject host = new JSONObject();
				// value:windows<a>(a:0-100) eg:windows32
				host.put("hostName", "wnode00" + (int) (Math.random() + 1));
				hosts.add(host);
			}
			result.put("hosts", hosts);
			results.add(result);
		}
		return results;
	}

	/**
	 * 获取文件系统的文件目录
	 * 
	 * @param root
	 * @return
	 */
	@SuppressWarnings("Duplicates")
	public static HttpResultList getFilePath(String root) {
		if (!HttpConfig.fake) {
			String fileUrl = HttpConfig.filePath;
			if (root == null || root.equals(null)) {
				root = "";
			} else {
				fileUrl = fileUrl + root;
			}
			// eg: root is a ,so fileUrl is
			// http://<hostname>:<port>/webhdfs/v1/home/a
			String param = "op=LISTSTATUS";
			List<Object> statuses;
			try {
				JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(fileUrl, param));
				result = result.getJSONObject("FileStatuses");
				JSONArray resultArray = result.getJSONArray("FileStatus");
				statuses = new ArrayList<>();
				for (int i = 0; i < resultArray.size(); i++) {
					JSONObject temp = resultArray.getJSONObject(i);
					FileStatus fileStatus = new FileStatus();
					// fileStatus.setAccessTime(temp.getString("accessTime"));
					// fileStatus.setBlockSize(temp.getString("blockSize"));
					// fileStatus.setChildrenNum(temp.getString("childrenNum"));
					// fileStatus.setFileId(temp.getString("fileId"));
					// fileStatus.setGroup(temp.getString("group"));
					fileStatus.setLength(temp.getString("length"));
					// fileStatus.setModificationTime(temp.getString("modificationTime"));
					// fileStatus.setOwner(temp.getString("owner"));
					fileStatus.setPathSuffix(temp.getString("pathSuffix"));
					// fileStatus.setPermission(temp.getString("permission"));
					// fileStatus.setReplication(temp.getString("replication"));
					// fileStatus.setStoragePolicy(temp.getString("storagePolicy"));
					fileStatus.setType(temp.getString("type"));
					statuses.add(fileStatus);
				}
				return new HttpResultList(true, "", statuses);
			} catch (net.sf.json.JSONException e) {
				e.printStackTrace();
				return new HttpResultList(false, "服务器返回值有误，请联系管理员！", null);
			}
		} else {
			if (root == null || root.equals(null) || root == "") {
				root = "";
			} else {
				root = root.substring(0, root.length() - 1);
				root = root.substring(root.lastIndexOf("/") + 1, root.length());
			}
			JsonUtil jsonUtil = new JsonUtil();
			String result = jsonUtil.getPathInforByRoot(root);
			return new HttpResultList(true, result, null);
		}

	}

	public static HttpResultList getFilePathNew(String root) {
		if (!HttpConfig.fake) {
			String ccToken = getStorageToken();
			if (ccToken.equals("error")) {
				return new HttpResultList(false, "error", null);
			}

			String fileUrl = HttpConfig.filePath;
			if (MyStringUtils.isEmpty(root)) {
				root = "/";
			} else {
				// fileUrl = fileUrl + root;
			}
			String param = "access_token=" + ccToken + "&path=" + root;
			Log4jInit.logger.info(param);
			List<Object> statuses;
			try {
				String ret = HttpsRequest.sendGet(fileUrl, param);
				JSONObject result = JSONObject.parseObject(ret.trim());
				// result = result.getJSONObject("data");
				JSONArray resultArray = result.getJSONArray("data");
				statuses = new ArrayList<>();
				for (int i = 0; i < resultArray.size(); i++) {
					JSONObject temp = resultArray.getJSONObject(i);
					FileStatus fileStatus = new FileStatus();
					// fileStatus.setLength(temp.getString("length"));
					fileStatus.setPathSuffix(temp.getString("file"));
					fileStatus.setType(temp.getString("isFolder").equals("true") ? "DIRECTORY" : "FILE");
					statuses.add(fileStatus);
				}
				return new HttpResultList(true, "", statuses);
			} catch (net.sf.json.JSONException e) {
				e.printStackTrace();
				return new HttpResultList(false, "服务器返回值有误，请联系管理员！", null);
			}
		} else {
			if (root == null || root.equals(null) || root == "") {
				root = "";
			} else {
				root = root.substring(0, root.length() - 1);
				root = root.substring(root.lastIndexOf("/") + 1, root.length());
			}
			JsonUtil jsonUtil = new JsonUtil();
			String result = jsonUtil.getPathInforByRoot(root);
			return new HttpResultList(true, result, null);
		}

	}
	
	public static HttpResultList getFilePathLocal(String root) {
		if (!HttpConfig.fake) {

			String fileUrl = HttpConfig.filePath;
			if (MyStringUtils.isEmpty(root)) {
				root = "/";
			} else {
				 fileUrl = fileUrl+"/" + root;
			}
			System.out.println("fileUrl  "+fileUrl);
			
			List<Object> statuses = new ArrayList<Object>();
			try {
				
				File filePath = new File(fileUrl);
				if(filePath.isDirectory()){
					File[] files = filePath.listFiles();
					List<File> fs = new ArrayList<File>();
					for(File f:files){
						fs.add(f);
					}
					List<File> sortFile = SortFile.sortByName(fs, "asc");
					for(File f:sortFile){
						LCStoreModel lc = new LCStoreModel();
//						System.out.println("file:"+f.getName());
						if(f.isDirectory()){
							lc.setType("DIRECTORY");
							lc.setPathSuffix(f.getName());
						}else{
							lc.setType("FILE");
							lc.setPathSuffix(f.getName());
						}
						statuses.add(lc);
					}
					
				}
				return new HttpResultList(true, "", statuses);
			} catch (net.sf.json.JSONException e) {
				e.printStackTrace();
				return new HttpResultList(false, "服务器返回值有误，请联系管理员！", null);
			}
		} else {
			if (root == null || root.equals(null) || root == "") {
				root = "";
			} else {
				root = root.substring(0, root.length() - 1);
				root = root.substring(root.lastIndexOf("/") + 1, root.length());
			}
			JsonUtil jsonUtil = new JsonUtil();
			String result = jsonUtil.getPathInforByRoot(root);
			return new HttpResultList(true, result, null);
		}

	}

	/**
	 * @param userName
	 *            : here not use
	 * @param passWord
	 *            : here not use
	 * @return token
	 */
	public static HttpResult getToken(String userName, String passWord) {
		if (!HttpConfig.fake) {
			String token = TokenValue.TOKEN.getTokenValue(HttpConfig.userName, HttpConfig.passWord);
			if (token != null) {
				return new HttpResult(true, token);
			} else {
				return new HttpResult(false, "服务器错误！");
			}
		} else {
			return new HttpResult(true, "fakeToken");
		}
	}

	public static void chmod(String filePath) throws IOException {
		/*
		 * if(HttpConfig.serverPlatform.equals("linux")) {
		 * Runtime.getRuntime().exec("chmod 777 " + filePath); }
		 */

		Process p = Runtime.getRuntime().exec("chmod 777 " + filePath);

		/* 为"错误输出流"单独开一个线程读取之,否则会造成标准输出流的阻塞 */
		Thread t = new Thread(new StreamGobbler(p.getErrorStream(), "ErrorStream"));
		t.start();

		try {
			p.waitFor();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			p.destroy();
		}
	}

	/**
	 * @param fileUri
	 *            返回上传到服务端的路径
	 */
	public static List<String> uploadFiles(boolean isAlgorithmFile, TaskThread fatherTask, String fileUri,
			String ftpFileUri, String algorithmName, String executeAlgorithmFileName, String algorithmHash) {
		List<String> result = new ArrayList<String>();
		try {
			List<String> fileMap = null;
			String uploadToolUri = HttpConfig.uploadToolUri;
			String rootPath = Thread.currentThread().getContextClassLoader().getResource("/").getPath();
			String postfix = "";
			if (HttpConfig.serverPlatform.equals("linux")) {
				uploadToolUri = rootPath + uploadToolUri;
				postfix = ".sh";
			} else {
				postfix = ".bat";
				rootPath = rootPath.substring(1, rootPath.length());
				uploadToolUri = rootPath + uploadToolUri;
			}
			chmod(uploadToolUri);
			if (isAlgorithmFile && fileUri.substring(fileUri.lastIndexOf("."), fileUri.length()).equals(".zip")) {
				/**
				 * 如果上传算法文件且文件格式是zip,将zip解压到同名文件夹,并取出当中所有文件的路径
				 */
				StaticUtil.unzip(fileUri);
				String dirPath = fileUri.substring(0, fileUri.lastIndexOf("."));
				String foldName = dirPath.substring(dirPath.lastIndexOf("/") + 1, dirPath.length());
				String targetFilePath = dirPath + "/";
				String iniFileUri = Thread.currentThread().getContextClassLoader().getResource("config.ini").getPath();
				boolean createIniFile = StaticUtil.createIniFile(null, algorithmHash, algorithmName, iniFileUri,
						targetFilePath,fatherTask.runningTaskBean.getTaskHash()) != null;
				if (!createIniFile)
					return null;
				// StaticUtil.cpFile(iniFileUri,targetFilePath);
				if (executeAlgorithmFileName == null)
					return null;
				fileMap = StaticUtil.getAllFiles(dirPath, foldName, executeAlgorithmFileName);
				for (int i = 0; i < fileMap.size(); i++) {
					fileUri = fileMap.get(i);
					// Log4jInit.logger.info("fileUri:"+ftpFileUri);
					// 远端路径重拼装
					ftpFileUri = ftpFileUri.substring(0, ftpFileUri.lastIndexOf("/"))
							+ fileUri.substring(fileUri.lastIndexOf("/"));
					updateState(ftpFileUri, generateScriptFile(ftpFileUri, fileUri, uploadToolUri, postfix), postfix,
							result, fatherTask);
					if (fileUri.contains(executeAlgorithmFileName)) {
						StaticUtil.deleteFile(fileUri);
					}
				}
			} else {
				/**
				 * 如果是其他情况，则ftpFileUri是早已封装好的，不需再处理
				 */
				updateState(ftpFileUri, generateScriptFile(ftpFileUri, fileUri, uploadToolUri, postfix), postfix,
						result, fatherTask);
			}
			return result;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	private static String generateScriptFile(String tempDir, String fileUri, String uploadToolUri, String postfix)
			throws IOException {

		if (fileUri.equals("") || fileUri.equals(null)) {
			return "";
		}

		String command = uploadToolUri + " -m " + HttpConfig.uploadIP + " -l " + fileUri + " -r " + tempDir
				+ " -u jhadmin";
		// Log4jInit.logger.info("command::"+command);
		String scriptFileUri = HttpConfig.scriptFileUri;
		File scriptFile = new File(scriptFileUri);
		if (!scriptFile.exists()) {
			scriptFile.mkdirs();
			chmod(scriptFileUri);
		}
		String scriptUri = scriptFileUri + UUID.randomUUID().toString().substring(0, 20) + postfix;

		File algorithmBatFile = new File(scriptUri);
		FileWriter fw = new FileWriter(algorithmBatFile);
		chmod(scriptUri);
		fw.write(command);
		fw.close();
		return scriptUri;

	}

	private static void updateState(String ftpFileUri, String batUri, String postfix, List<String> result,
			TaskThread fatherTask) {
		if (batUri.equals("")) {
			fatherTask.updateState("上传文件时，本地文件为空");
			return;
		}
		if (createFolders(ftpFileUri)) {
			fatherTask.updateState("上传文件时，创建目录成功");
			if ((!batUri.equals("")) && runBat(batUri)) {
				StaticUtil.deleteFile(batUri);
				fatherTask.updateState("上传文件时，运行" + postfix + "文件成功");
				result.add(ftpFileUri);
			} else {
				fatherTask.updateState("上传文件时，运行" + postfix + "文件失败");
			}
		} else {
			fatherTask.updateState("上传文件时，创建目录失败");
		}
	}

	private static boolean createFolders(String ftpFileUri) {
		if (!HttpConfig.fake) {
			String targetUri = ftpFileUri.substring(0, ftpFileUri.lastIndexOf("/") + 1);
			String params = "dirpath=" + targetUri + "&isforce=true&token="
					+ getToken(HttpConfig.userName, HttpConfig.passWord).getMessage();
			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(HttpConfig.createFtpFolder, params));
			if (result.getString("result").equals("success")) {
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
	}

	/**
	 * @param token
	 * @return success:GROUP_NAME fail:message
	 */
	public static HttpResult getHostGroupList(String token) {
		if (!HttpConfig.fake) {
			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(HttpConfig.hostGroupUrl, "token=" + token));
			if (result.getString("result").equals("success")) {
				JSONObject hostGroup = result.getJSONArray("data").getJSONObject(0);
				return new HttpResult(true, hostGroup.getString("GROUP_NAME"));
			} else {
				return new HttpResult(false, result.getString("message"));
			}
		} else {
			return new HttpResult(true, "wingroup");
		}

	}

	/**
	 * @param commitJob
	 * @return success:jobId fail:message
	 */
	public static HttpResult startJob(CommitJob commitJob) {
		Log4jInit.logger.info("-------START Algrithm TIME : " + Time.now());
		if (!HttpConfig.fake) {
			Log4jInit.logger.info("commitJob param:" + commitJob.getRequestParam());
			String tempResult = HttpRequest.sendPost(HttpConfig.commitJob, commitJob.getRequestParam());
			Log4jInit.logger.info("commitJob result:" + tempResult);
			JSONObject result = JSONObject.parseObject(tempResult);
			SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss");
			Log4jInit.logger.info("-------Task complete::" + sf.format(new Date()));
			if (result.getString("result").equals("success")) {
				String jobId = result.getJSONArray("data").getString(0);
				return new HttpResult(true, jobId);
			} else {
				return new HttpResult(false, result.getString("message"));
			}
		} else {
			return new HttpResult(true, UUID.randomUUID().toString().substring(0, 20));
		}

	}

	/**
	 * @param ids
	 * @param token
	 * @return success fail :message
	 */
	@SuppressWarnings("Duplicates")
	public static HttpResult stopJob(List<String> ids, String token) {
		if (!HttpConfig.fake) {
			// String id = "id=";
			String actUrl = "";
			String tempPara = "";
			String id = "";
			for (String oneId : ids) {
				id += oneId + ",";
				actUrl = HttpConfig.stateQueryUrl + "kill/" + id;
				tempPara = "token=" + token;
				actUrl = actUrl.substring(0, actUrl.lastIndexOf(","));
			}
			/*
			 * for (int i=0;i<ids.size();i++) { String oneId = ids.get(i); id +=
			 * oneId + ","; if(i==1){ // id = "id=" + id; actUrl =
			 * HttpConfig.stopJob; tempPara = "token=" + token +"&id="+id;
			 * tempPara = tempPara.substring(0, tempPara.lastIndexOf(","));
			 * }else if(i==0){ actUrl = HttpConfig.stateQueryUrl+"kill/"+id;
			 * tempPara = "token=" + token; actUrl = actUrl.substring(0,
			 * actUrl.lastIndexOf(",")); }else{ tempPara = "token=" + token
			 * +"&"+id; tempPara = tempPara.substring(0,
			 * tempPara.lastIndexOf(",")); } }
			 */

			// id = id.substring(0, id.lastIndexOf(","));
			Log4jInit.logger.info("STOP:" + tempPara);
			Log4jInit.logger.info("STOP URL:" + actUrl);

			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(actUrl, tempPara));
			if (result.getString("result").equals("success")) {
				return new HttpResult(true, result.getString("message"));
			} else {
				return new HttpResult(false, result.getString("message"));
			}
		} else {
			String id = "停止id组成功：";
			for (String oneId : ids) {
				id += oneId + ",";
			}
			id = id.substring(0, id.lastIndexOf(","));
			return new HttpResult(true, id);
		}
	}

	/**
	 * 通过作业id暂停一组正在运行的作业
	 * 
	 * @param ids
	 * @param token
	 * @return
	 */
	public static HttpResult restartJob(List<String> ids, String token) {
		if (!HttpConfig.fake) {
			String actUrl = "";
			String tempPara = "";
			String id = "";
			for (String oneId : ids) {
				id += oneId + ",";
				actUrl = HttpConfig.stateQueryUrl + "resume/" + id;
				tempPara = "token=" + token;
				actUrl = actUrl.substring(0, actUrl.lastIndexOf(","));
			}

			Log4jInit.logger.info("RESTART:" + tempPara);
			Log4jInit.logger.info("RESTART URL:" + actUrl);
			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(actUrl, tempPara));
			if (result.getString("result").equals("success")) {
				return new HttpResult(true, result.getString("message"));
			} else {
				return new HttpResult(false, result.getString("message"));
			}
		} else {
			String id = "重启id组成功：";
			for (String oneId : ids) {
				id += oneId + ",";
			}
			id = id.substring(0, id.lastIndexOf(","));
			return new HttpResult(true, id);
		}
	}

	/**
	 * 通过作业id暂停一组正在运行的作业
	 * 
	 * @param ids
	 * @param token
	 * @return
	 */
	public static HttpResult pauseJob(List<String> ids, String token) {
		if (!HttpConfig.fake) {
			String actUrl = "";
			String tempPara = "";
			String id = "";
			for (String oneId : ids) {
				id += oneId + ",";
				actUrl = HttpConfig.stateQueryUrl + "stop/" + id;
				tempPara = "token=" + token;
				actUrl = actUrl.substring(0, actUrl.lastIndexOf(","));
			}

			Log4jInit.logger.info("PAUSE:" + tempPara);
			Log4jInit.logger.info("PAUSE URL:" + actUrl);
			JSONObject result = JSONObject.parseObject(HttpRequest.sendGet(actUrl, tempPara));
			if (result.getString("result").equals("success")) {
				return new HttpResult(true, result.getString("message"));
			} else {
				return new HttpResult(false, result.getString("message"));
			}
		} else {
			String id = "暂停id组成功：";
			for (String oneId : ids) {
				id += oneId + ",";
			}
			id = id.substring(0, id.lastIndexOf(","));
			return new HttpResult(true, id);
		}
	}

	/**
	 * HttpResultList.message:获取资源成功 or 005：用户验证失败
	 *
	 * @param token
	 * @return
	 */
	@SuppressWarnings("Duplicates")
	public static HttpResultList getJobBasicState(String token) {
		if (!HttpConfig.fake) {
			JSONObject result = JSONObject
					.parseObject(HttpRequest.sendGet(HttpConfig.getBaseResourceStateUrl, "token=" + token));
			// Log4jInit.logger.info("查询基础状态的返回值：："+result.toString());
			if (result.getString("result").equals("success")) {
				JSONArray data = result.getJSONArray("data");
				List<Object> states = new ArrayList<>();
				for (int i = 0; i < data.size(); i++) {
					BaseResourceState state = new BaseResourceState();
					JSONObject oneData = data.getJSONObject(i);
					state.setHostName(oneData.getString("HOST_NAME"));
					state.setStatus(oneData.getString("status"));
					state.setR15s(oneData.getString("r15s"));
					state.setR1m(oneData.getString("r1m"));
					state.setR15m(oneData.getString("r15m"));
					state.setUt(oneData.getString("ut"));
					state.setPg(oneData.getString("pg"));
					state.setLs(oneData.getString("ls"));
					state.setIt(oneData.getString("it"));
					state.setTmp(oneData.getString("tmp"));
					state.setSwp(oneData.getString("swp"));
					state.setMem(oneData.getString("mem"));
					state.setType(oneData.getString("type"));
					states.add(state);
				}
				return new HttpResultList(true, result.getString("message"), states);
			} else {
				return new HttpResultList(false, result.getString("message"), null);
			}
		} else {
			List<Object> states = new ArrayList<>();
			for (int i = 0; i < 15; i++) {
				BaseResourceState state = new BaseResourceState();
				state.setHostName("wnode0" + i);
				state.setStatus("ok");
				state.setR15s("0.0");
				state.setR1m("0.1");
				state.setR15m("0.6");
				state.setUt("1%");
				state.setPg("0.0");
				state.setLs("0");
				state.setIt("-");
				state.setTmp("196G");
				state.setSwp("3982M");
				state.setMem("3054M");
				state.setType("NTX64");
				states.add(state);
			}
			return new HttpResultList(true, "获取资源成功", states);
		}
	}

	/**
	 * run the bat file in batUri
	 *
	 * @param batUri
	 */
	private static boolean runBat(String batUri) {
		boolean result = false;
		if (!HttpConfig.fake) {
			Process p;
			try {
				chmod(batUri);
				// 执行命令
				p = Runtime.getRuntime().exec(batUri);
				// Log4jInit.logger.info("====exec:"+batUri);
				// 取得命令结果的输出流
				InputStream fis = p.getInputStream();
				// 用一个读输出流类去读
				InputStreamReader isr = new InputStreamReader(fis, "gbk");
				// 用缓冲器读行
				BufferedReader br = new BufferedReader(isr);
				String line = null;
				// 直到读完为止
				while ((line = br.readLine()) != null) {
					if (line.equals("upload file success")) {
						result = true;
					}
				}
				File f = new File(batUri);
				f.delete();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		} else {
			return true;
		}
	}

	/**
	 * real single job full state query
	 *
	 * @param jobId
	 * @param token
	 * @return
	 * @throws IOException
	 */
	public static HttpResultList getJobFullState(String jobId, String token) throws IOException {
		if (!HttpConfig.fake) {
			try {
				Thread.currentThread().sleep(Long.parseLong("1000"));
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			String callbackResult = HttpRequest.sendGet(HttpConfig.stateQueryUrl + jobId, "token=" + token);
			if (!callbackResult.equals(null)) {
				callbackResult = callbackResult.replaceAll("\\\\\\\\", "\\\\");
				callbackResult = callbackResult.replaceAll("\\\\", "\\\\\\\\");
			}
			JSONObject result = JSONObject.parseObject(callbackResult);
			return pickFullJobState(result, jobId);
		} else {
			JsonUtil jsonUtil = new JsonUtil();
			String ggResult = jsonUtil.getFullJobState().replaceAll("\\\\", "/");
			JSONObject result = JSONObject.parseObject(ggResult);
			return pickFullJobState(result, jobId);
		}
	}

	@SuppressWarnings("Duplicates")
	public static HttpResultList pickFullJobState(JSONObject result, String jobId) {
		if (result.getString("result").equals("success")) {
			JSONArray data = result.getJSONArray("data");
			List<Object> states = new ArrayList<>();
			for (int i = 0; i < data.size(); i++) {
				FullJobState state = new FullJobState();
				JSONObject oneData = data.getJSONObject(i);
				state.setJobId(jobId);
				state.setIndex(oneData.getString("index"));
				state.setOwner(oneData.getString("owner"));
				// state.setOwner(oneData.getString("executionHost"));
				state.setStatus(oneData.getString("status"));
				state.setJobName(oneData.getString("name"));
				state.setQueue(oneData.getString("queue"));
				state.setCommand(oneData.getString("command"));
				state.setNewCommand(oneData.getString("newCommand"));
				state.setPendingOrder(oneData.getString("pendingOrder"));
				state.setExecHome(oneData.getString("execHome"));
				state.setExecutionCWD(oneData.getString("executionCWD"));
				state.setExecUsername(oneData.getString("execUsername"));
				state.setCpuTime(oneData.getString("cpuTime"));
				state.setUmask(oneData.getString("umask"));
				state.setCpuFactor(oneData.getString("cpuFactor"));
				state.setExitCode(oneData.getString("exitCode"));
				state.setExecUid(oneData.getString("execUid"));
				state.setPriority(oneData.getString("priority"));
				state.setSubHomeDir(oneData.getString("subHomeDir"));
				state.setSubmitHost(oneData.getString("submitHost"));
				state.setRequestGpuNum(oneData.getString("requestGpuNum"));
				// state.setjType(oneData.getString("jType"));
				state.setExecutionHost(oneData.getString("executionHost"));
				state.setBindGpu(oneData.getString("bindGPU"));
				state.setReason(oneData.getString("reasons"));
				state.setSumRusage(oneData.getString("sumRusage"));
				state.setHostsRusage(oneData.getString("hostsRusage"));
				state.setRequestResources(oneData.getString("requestResources"));
				state.setHostSpec(oneData.getString("hostSpec"));
				state.setInFile(oneData.getString("inFile"));
				state.setOutFile(oneData.getString("outFile"));
				state.setErrFile(oneData.getString("errFile"));
				state.setChkpntDir(oneData.getString("chkpntDir"));
				state.setPreExecCmd(oneData.getString("preExecCmd"));
				state.setMailUser(oneData.getString("mailUser"));
				state.setProject(oneData.getString("project"));
				state.setLoginShell(oneData.getString("loginShell"));
				state.setDependCond(oneData.getString("dependCond"));
				state.setSlots(oneData.getString("slots"));
				state.setSigValue(oneData.getString("sigValue"));
				state.setMaxNumProcessors(oneData.getString("maxNumProcessors"));
				// state.setNumProcessors(oneData.getString("maxNumProcessors"));
				state.setUserPriority(oneData.getString("userPriority"));
				state.setAskedHosts(oneData.getString("askedHosts"));
				state.setSubmitTime(oneData.getString("submitTime"));
				state.setExecutionTime(oneData.getString("executionTime"));
				state.setTerminationTime(oneData.getString("terminationTime"));
				state.setReserveTime(oneData.getString("reserveTime"));
				state.setjRusageUpdateTime(oneData.getString("jRusageUpdateTime"));
				state.setPredictedStartTime(oneData.getString("predictedStartTime"));
				state.setArrayJob(oneData.getString("arrayJob"));
				state.setDesktopid(oneData.getString("desktopid"));
				state.setGroup(oneData.getString("group"));
				state.setMemUsage(oneData.getString("memUsage"));
				state.setSwapUsage(oneData.getString("swapUsage"));
				state.setCpuUsage(oneData.getString("cpuUsage"));
				// state.setSecretLevel(oneData.getString("secretLevel"));
				// state.setCwd(oneData.getString("cwd"));
				states.add(state);
			}
			return new HttpResultList(true, result.getString("message"), states);
		} else {
			return new HttpResultList(false, result.getString("message"), null);
		}
	}

	private static String getStorageToken() {

		String fileUrl = HttpConfig.storageServer + "/oauth/token";
		// String param =
		// "grant_type=client_credentials&client_secret=c7Q7piGGhNJSrTRu&client_id=32API";
		String param = "grant_type=" + HttpConfig.grant_type + "&client_secret=" + HttpConfig.client_secret
				+ "&client_id=" + HttpConfig.client_id;
		System.out.println(param);
		String out = HttpsRequest.sendGet(fileUrl, param);
		// JSONObject result = JSONObject.parseObject(JSON.toJSONString(out.trim()));
		JSONObject result = JSONObject.parseObject(out.trim());
		System.out.println("res:" + result);
		if (result.isEmpty() || result.containsKey("error"))
			return "error";
		return result.getString("value");
	}
	


	public static void main(String[] args) {
//		String out = AlgorithmOperator.getStorageToken();
		HttpResultList o = AlgorithmOperator.getFilePathLocal("");
		for(Object m:o.getDatas()){
			LCStoreModel mm = (LCStoreModel)m;
			System.out.println(mm.getPathSuffix()+"==="+mm.getType());
		}
		
	}
}